var drawer = {
    plumbIns: null,
    starting: 0,//启动中  0否1是
    saved: false,
    sourceModel: {},//打开页面时最初加载的modejson
    model: {
        id: '',
        name: '',
        params: '',
        lineList: [],
        nodeList: []
    },
    activeElement: {
        type: '',
        id: '',
    },
    modelId: '',
    modelName: '',
    modelParams : '',
    newNodeTop:  120,
    nodeList: [],
    lineList: [],
    nodeIdList: [],//记录node的id
    relations: [],//记录节点关联
    containConfig: { //容器的配置：10像素为单位移动方便元素对齐
        containment: 'diagramContainer',
        grid: [10, 10],
        stop: function (el) {
            //拖动节点放开时，要更新下left 和 top
            // console.log(el)
            var nodeId = el.el.id;
            var left = el.el.offsetLeft;
            var top = el.el.offsetTop;
            for (var i = 0; i < drawer.nodeList.length; i++) {
                if(drawer.nodeList[i].id === nodeId){
                    drawer.nodeList[i].left = left + 'px';
                    drawer.nodeList[i].top = top + 'px';
                    break;
                }
            }
            drawer.viewModelJson();
        }
    },
    commonConfig: {
        isSource: true,
        isTarget: true,
        connector: 'Flowchart',
        endpoint: 'Rectangle',//锚点样式：Blank/Dot/Image/Rectangle
        paintStyle: { stroke: '#909399', strokeWidth: 1 },
        hoverPaintStyle: {
            outlineStroke: 'lightblue'
        },
        connectorStyle: {
            outlineStroke: '#909399',
            strokeWidth: 1
        },
        connectorHoverStyle: {
            strokeWidth: 2
        },
        overlays: [ ['Arrow', { width: 8, length: 8, location: 0.8 }] ],
        maxConnections: -1, //不限制一个端点能拖出的线的数量
        ConnectionsDetachable: false, //禁止拖放删除
    },
};

drawer.plumbIns = jsPlumb.getInstance({
    ConnectionOverlays: [
        ["Label", { label: "", id: "label-1", location:0.5, labelStyle: {color: 'white'}}]//默认的连线label样式
    ],
});

//显示导出模型的窗口
// drawer.initModelImportForm = function(){
//     $('#import_form').removeClass('hide');
//
// }

drawer.import = function(){
    if($('#modelLists').val()===''){
        drawer.sourceModel = JSON.parse($('#model_json').val());
        drawer.sourceModel.id = '';
        drawer.ready();
    }
}

//页面加载完执行
drawer.ready = function(){
    if($('#modelLists').val()===''){
        $('#import_form').removeClass('hide');
    }else{
        $('#import_form').addClass('hide');
    }
    //加载源数据
    var data = drawer.sourceModel
    drawer.modelId = data.id;
    drawer.modelName = data.name;
    drawer.modelParams = data.params;
    $('#model_name').val(drawer.modelName);
    $('#model_params').val(drawer.modelParams);
    drawer.nodeList = data.nodeList;
    drawer.lineList = data.lineList;
    //绘制节点
    drawer.node.initNode();
    //绘制连线 和 锚点
    drawer.start();
}
//关于node的操作
drawer.node = {
    initNode: function(){//页面加载，初始化节点
        for (var i = 0; i < drawer.nodeList.length; i++) {
            var node = eval(drawer.nodeList[i]);
            //记录nodeid
            drawer.nodeIdList.push(node.id);
            //放入容器
            drawer.node.putDown(node.type, node.id, node.name, node.top, node.left);
        }
        //记录节点关联关系
        for (var i = 0; i < drawer.lineList.length; i++) {
            drawer.relations.push([drawer.lineList[i].fromNodeId, drawer.lineList[i].toNodeId])
        }
    },
    resetNodeForm: function(){
        $('#node_id').val('');
        $('#node_name').val('');
        $('#node_type').val('');
        $('#node_top').val('');
        $('#node_left').val('');
    },
    initNodeForm: function(e,nodeId){
        $('#import_form').addClass('hide');
        $('#line_form').addClass('hide');
        $('#node_form').removeClass('hide');
        this.resetNodeForm();
        for (var i = 0; i < drawer.nodeList.length; i++) {
            var node = drawer.nodeList[i];
            if(node.id === nodeId){
                $('#node_id').val(node.id);
                $('#node_name').val(e.innerHTML);
                $('#node_type').val(node.type);
                $('#node_top').val(e.style.top);
                $('#node_left').val(e.style.left);
                break;
            }
        }
        drawer.plumbIns.draggable(nodeId, drawer.containConfig);
    },
    saveNodeForm: function(){
        if($('#node_id').val()!=''){
            $('#' + $('#node_id').val()).html($('#node_name').val())

            for (var i = 0; i < drawer.nodeList.length; i++) {
                if(drawer.nodeList[i].id === $('#node_id').val()){
                    drawer.nodeList[i].name = $('#node_name').val();
                }
            }
            drawer.viewModelJson();
            alert('success');
        }
    },
    delNode: function(){
        var nodeId = $('#node_id').val();
        if(nodeId!=''){
            if (window.prompt('确定删除选中节点吗？ 输入123确定') === '123') {
                //删除节点前，需要删除节点的全部连接线（出线 和 入线）
                for (var i = 0; i < drawer.lineList.length; i++) {
                    if(drawer.lineList[i].fromNodeId === nodeId||drawer.lineList[i].toNodeId === nodeId){
                        alert('需先删除该节点所有连接线');
                        return;
                    }
                }
                //删除锚点、节点、nodelist信息
                this.deleteEmptyEndpoints($('#node_id').val());
                $('#' + $('#node_id').val()).remove();
                drawer.nodeList = drawer.nodeList.filter(function (node) {
                    if (node.id === nodeId) {
                        return false
                    }
                    return true
                })
                drawer.viewModelJson();
            }
        }
    },
    deleteEmptyEndpoints: function(element){//删除锚点
        var endpoints_to_delete = [];
        drawer.plumbIns.selectEndpoints({source:element}).each(function(endpoint) {
            // console.log(endpoint);
            if( !!endpoint && endpoint.connections.length <= 0 )
            {
                // console.log('marking ' + endpoint.getId() + ' for deletion');
                endpoints_to_delete.push(endpoint);
            }
        });
        $.each(endpoints_to_delete, function(index, endpoint) {
            // console.log('deleting endpoint: ' + endpoint);
            drawer.plumbIns.deleteEndpoint(endpoint);
            // console.log('endpoint deleted');

        });
    },
    addBeginNode: function(){//新增起点
        var newNodeId = drawer.randomString(30);
        var top = drawer.newNodeTop;
        var left = 10;
        var name = '开始';
        var type = 'begin';
        //放入容器
        drawer.node.putDown(type, newNodeId, name, top, left);
        //加入nodeList
        drawer.nodeList.push({
            "ico" : "",
            "id" : newNodeId,
            "left" : left + 'px',
            "name" : name,
            "top" : top + 'px',
            "type" : type
        })
        drawer.plumbIns.draggable(newNodeId, drawer.containConfig);
        //增加锚点，并设置可拖动
        drawer.node.addPoint(newNodeId);
        drawer.viewModelJson();
    },
    addEndNode: function(){//新增终点
        var newNodeId = drawer.randomString(30);
        var top = drawer.newNodeTop;
        var left = 10;
        var name = '结束';
        var type = 'end';
        //放入容器
        drawer.node.putDown(type, newNodeId, name, top, left);
        //加入nodeList
        drawer.nodeList.push({
            "ico" : "",
            "id" : newNodeId,
            "left" : left + 'px',
            "name" : name,
            "top" : top + 'px',
            "type" : type
        })
        drawer.plumbIns.draggable(newNodeId, drawer.containConfig);
        //增加锚点，并设置可拖动
        drawer.node.addPoint(newNodeId);
        drawer.viewModelJson();
    },
    addGatewayNode: function(){//新增网关
        var newNodeId = drawer.randomString(30);
        var top = drawer.newNodeTop;
        var left = 10;
        var name = '结束';
        var type = 'gateway';
        //放入容器
        drawer.node.putDown(type, newNodeId, name, top, left);
        //加入nodeList
        drawer.nodeList.push({
            "ico" : "",
            "id" : newNodeId,
            "left" : left + 'px',
            "name" : name,
            "top" : top + 'px',
            "type" : type
        })
        drawer.plumbIns.draggable(newNodeId, drawer.containConfig);
        //增加锚点，并设置可拖动
        drawer.node.addPoint(newNodeId);
        drawer.viewModelJson();
    },
    addTaskNode: function(){//新增节点
        var newNodeId = drawer.randomString(30);
        var top = drawer.newNodeTop;
        var left = 10;
        var name = 'new task';
        var type = 'task';
        //放入容器
        drawer.node.putDown(type, newNodeId, name, top, left);
        //加入nodeList
        drawer.nodeList.push({
            "ico" : "",
            "id" : newNodeId,
            "left" : left + 'px',
            "name" : name,
            "top" : top + 'px',
            "type" : type
        })
        drawer.plumbIns.draggable(newNodeId, drawer.containConfig);
        //增加锚点，并设置可拖动
        drawer.node.addPoint(newNodeId);
        drawer.viewModelJson();
    },
    putDown: function (type, nodeId, nodeName, top, left) {//绘制节点到容器中
        var nodeHtml = '';
        if(type === 'task'){
            nodeHtml = '<div id="'+ nodeId +'" class="state-item" ' +
                'onclick="drawer.node.initNodeForm(this,\''+ nodeId +'\')">' + nodeName + '</div>';
        }else if(type === 'begin'){
            nodeHtml = '<div id="'+ nodeId +'" class="state-item-begin" ' +
                'onclick="drawer.node.initNodeForm(this,\''+ nodeId +'\')">' + nodeName + '</div>';
        }else if(type === 'end'){
            nodeHtml = '<div id="'+ nodeId +'" class="state-item-end" ' +
                'onclick="drawer.node.initNodeForm(this,\''+ nodeId +'\')">' + nodeName + '</div>';
        }else if(type === 'gateway'){
            nodeHtml = '<div id="'+ nodeId +'" class="state-item-gateway" ' +
                'onclick="drawer.node.initNodeForm(this,\''+ nodeId +'\')">' + '+' + '</div>';
        }
        if(nodeHtml!=''){
            $('#diagramContainer').html($('#diagramContainer').html() + nodeHtml);
            $('#' + nodeId).css({top: top, left: left});
        }
    },
    addPoint: function(nodeId){//绘制锚点
        drawer.plumbIns.addEndpoint(nodeId, {
            uuid: nodeId + '_top',
            anchor: ["Top"]
        }, drawer.commonConfig);
        drawer.plumbIns.addEndpoint(nodeId, {
            uuid: nodeId + '_right',
            anchor: "Right"
        }, drawer.commonConfig);
        drawer.plumbIns.addEndpoint(nodeId, {
            uuid: nodeId + '_left',
            anchor: "Left"
        }, drawer.commonConfig);
        drawer.plumbIns.addEndpoint(nodeId, {
            uuid: nodeId + '_bottom',
            anchor: "Bottom"
        }, drawer.commonConfig);
    }
}

drawer.delRelation = function(sourceId, targetId){
    //删除关联
    drawer.relations = drawer.relations.filter(function (relation) {
        if (relation[0] == sourceId && relation[1] == targetId) {
            return false
        }
        // console.log('relations:' + drawer.relations)
        return true
    })
}

drawer.addRelation= function(sourceId, targetId){
    drawer.relations.push([sourceId, targetId]);
    // console.log('relations:' + drawer.relations)
}

//绘制
drawer.start = function(){
    drawer.starting = 1;
    for (var i = 0; i < drawer.relations.length; i++) {
        for (var j = 0; j < drawer.lineList.length; j++) {
            if(drawer.lineList[j].fromNodeId == drawer.relations[i][0]
                    &&drawer.lineList[j].toNodeId == drawer.relations[i][1]){
                drawer.plumbIns.connect({
                    source: drawer.relations[i][0],
                    target: drawer.relations[i][1],
                    anchors: [drawer.lineList[j].outAnchor, drawer.lineList[j].inAnchor]
                }, drawer.commonConfig);
                drawer.line.saveLineInfo(
                    drawer.relations[i][0],
                    drawer.relations[i][1],
                    drawer.lineList[j].label,
                    drawer.lineList[j].cadidatesMethod,
                    drawer.lineList[j].cadidates,
                    drawer.lineList[j].flowCondition,
                    drawer.lineList[j].completeMethod,
                    drawer.lineList[j].asyncCompleteMethod
                );
            }
        }
    }
    //设置节点可拖动,为每个节点在四个方向锚点
    for (var i = 0; i < drawer.nodeIdList.length; i++) {
        drawer.plumbIns.draggable(drawer.nodeIdList[i], drawer.containConfig);
        drawer.node.addPoint(drawer.nodeIdList[i]);
    }
    drawer.viewModelJson();
    drawer.starting = 0;
}

//‘线’表单的操作
drawer.line = {
    resetLineForm: function(){
        $('#line_label').val('')
        $('#line_sourceId').val('')
        $('#line_targetId').val('')
        $('#line_id').val('')
    },
    //基于起止节点获取线的信息
    initLineForm: function (sourceId, targetId) {
        $('#import_form').addClass('hide');
        $('#node_form').addClass('hide');
        $('#line_form').removeClass('hide');
        this.resetLineForm();
        for (var i = 0; i < drawer.lineList.length; i++) {
            var line = drawer.lineList[i];
            if(sourceId === line.fromNodeId && targetId === line.toNodeId){
                $('#line_label').val(line.label)
                $('#line_sourceId').val(line.fromNodeId)
                $('#line_targetId').val(line.toNodeId)
                $('#line_id').val(line.id)
                break;
            }
        }
    },
    //保存‘线’表单
    saveLineForm: function(){
        if($('#line_sourceId').val()===''||$('#line_targetId').val()===''||$('#line_id').val()===''){
            alert('缺少起止节点');
        }else{
            this.saveLineInfo(
                $('#line_sourceId').val(),
                $('#line_targetId').val(),
                $('#line_label').val()
            );
        }
    },
    //保存‘线’信息，包括两个步骤：
    // 1.更新图上的线，主要是label
    // 2.更新lineList里的线的各种属性
    saveLineInfo: function(sourceId, targetId, labelTxt){
        //1.更新图上的线
        var conn = drawer.plumbIns.getConnections({
            source: sourceId,
            target: targetId
        })[0];
        if(conn){
            // console.log(conn)
            var labelStyle = conn.getOverlay("label-1");
            labelStyle.setLabel(labelTxt);

            //2.更新lineList里的线的各种属性
            for (var i = 0; i < drawer.lineList.length; i++) {
                if(drawer.lineList[i].fromNodeId == sourceId && drawer.lineList[i].toNodeId == targetId){
                    drawer.lineList[i].label = labelTxt;
                    break;
                }
            }
            drawer.viewModelJson();
            if(drawer.starting==0){
                alert('success');
            }
        }
    },
    //判断线是否存在
    existsLine: function(sourceId, targetId){
        for (var j = 0; j < drawer.lineList.length; j++) {
            if(drawer.lineList[j].fromNodeId === sourceId
                &&drawer.lineList[j].toNodeId === targetId){
                return true;
            }
        }
        return false;
    },
    //删除线
    delLine: function(sourceId, targetId){
        if(sourceId!=''&&targetId!=''){
            var conn = drawer.plumbIns.getConnections({
                source: sourceId,
                target: targetId
            })[0];
            if (window.prompt('确定删除选中的连接吗？ 输入123确定') === '123') {
                drawer.plumbIns.deleteConnection(conn)
                //移出lineList
                drawer.lineList = drawer.lineList.filter(function (line) {
                    if (line.fromNodeId == sourceId && line.toNodeId == targetId) {
                        return false
                    }
                    return true
                })
                drawer.delRelation(sourceId, targetId);
                drawer.viewModelJson();
            }
        }
    }
}

//点击连接线
drawer.plumbIns.bind('click', function (conn) {
    // console.log(conn)
    drawer.line.initLineForm(conn.sourceId, conn.targetId)
})

//手动拖放线，松开鼠标时触发
drawer.plumbIns.bind("beforeDrop", function(conn) {
    drawer.viewModelJson();
    var from = conn.sourceId
    var to = conn.targetId
    if (from === to) {
        alert('节点不支持连接自己')
        return false
    }
    if (drawer.line.existsLine(from, to)) {
        alert('该关系已存在,不允许重复创建')
        return false
    }
    return true
})
//连线成功触发
drawer.plumbIns.bind('connection', function (conn) {
    // console.log(conn)
    //为新拖出来的连接线，添加箭头
    drawer.plumbIns.select(conn).addOverlay(['Arrow', { width: 8, length: 8, location: 0.8 }]);

    //起止node的id，出/入 锚点的id
    var sourceId = conn.sourceId;
    var targetId = conn.targetId;
    var sourceEndpointId = '';
    if(conn.sourceEndpoint.anchor.type){
        sourceEndpoint = conn.sourceEndpoint.anchor.type;
    }else{
        sourceEndpoint = conn.sourceEndpoint.anchor.anchors[0].type;
    }
    var targetEndpointId = '';
    if(conn.targetEndpoint.anchor.type){
        targetEndpointId = conn.targetEndpoint.anchor.type;
    }else{
        targetEndpointId = conn.targetEndpoint.anchor.anchors[0].type;
    }
    // console.log(conn)
    //清空一下line表单
    drawer.line.resetLineForm();
    // //不允许自连
    // if(sourceId === targetId){
    //     alert('不允许自连');
    //     //重新触发绘制，以此解决本函数内删除当前线的问题
    //     drawer.start();
    //     return false;
    // }
    //重复连接
    if(drawer.line.existsLine(sourceId, targetId)){
        // alert('不允许重复连接');
        return false;
    }
    //能走到这里说明是全新绘制的线，需要加入仅lineList里
    var line = {
        "fromNodeId": sourceId,
        "toNodeId": targetId,
        "id": drawer.randomString(30),
        "inAnchor": targetEndpointId,
        "label": '',
        "outAnchor": sourceEndpointId,
    };
    drawer.lineList.push(line);
    drawer.addRelation(line.fromNodeId, line.toNodeId);
    drawer.viewModelJson();
})

//预览线集合json
drawer.viewLineListJson = function(){
    $('#viewJson').html(JSON.stringify(drawer.lineList));
}
//预览完整模型json
drawer.viewModelJson = function(){
    drawer.model.name = $('#model_name').val();
    drawer.model.params = $('#model_params').val();
    drawer.model.id = drawer.modelId;
    drawer.model.nodeList = drawer.nodeList;
    drawer.model.lineList = drawer.lineList;
    $('#viewJson').html(JSON.stringify(drawer.model).replaceAll(",\"", ",<br/>\""));
    return drawer.model;
}

//下载model
drawer.download = function(){
	if($('#model_name').val()===''){
		alert('先填写模型名称');
		return;
	}
    var datastr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(drawer.viewModelJson(), null, '\t'));
        var downloadAnchorNode = document.createElement('a')
        downloadAnchorNode.setAttribute("href", datastr);
        downloadAnchorNode.setAttribute("download", $('#model_name').val() + '.json')
        downloadAnchorNode.click();
        downloadAnchorNode.remove();
        drawer.saved = false;
}

//随机字符串
drawer.randomString = function(len){
    len = len || 32;
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length;
    var str = '';
    for (i = 0; i < len; i++) {
        str += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return str;
}
